package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.domain.Brand;
import com.spzx.product.domain.CategoryBrand;
import com.spzx.product.mapper.BrandMapper;
import com.spzx.product.mapper.CategoryBrandMapper;

import com.spzx.product.service.ICategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author ChenXing
 * @Description
 * @Create 2024/7/28 17:53
 */
@Service
public class CategoryBrandServiceImpl extends ServiceImpl<CategoryBrandMapper, CategoryBrand> implements ICategoryBrandService {

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private BrandMapper brandMapper;


    @Override
    public List<CategoryBrand> selectCategoryBrandList(CategoryBrand categoryCategoryBrand) {
        return categoryBrandMapper.selectCategoryBrandList(categoryCategoryBrand);
    }

    @Override
    public int updateCategoryBrand(CategoryBrand categoryBrand) {
        CategoryBrand originalCategoryBrand = this.getById(categoryBrand.getId());
        if(categoryBrand.getCategoryId().longValue() != originalCategoryBrand.getCategoryId().longValue()
                || categoryBrand.getBrandId().longValue() != originalCategoryBrand.getBrandId().longValue()) {
            long count = categoryBrandMapper.selectCount(new LambdaQueryWrapper<CategoryBrand>().eq(CategoryBrand::getCategoryId, categoryBrand.getCategoryId()).eq(CategoryBrand::getBrandId, categoryBrand.getBrandId()));
            if(count > 0) {
                throw new ServiceException("该分类已加该品牌");
            }
        }
        int i = categoryBrandMapper.updateById(categoryBrand);
        return i ;
    }

    @Override
    public List<Brand> getBrandListByCategory(Long id) {
        // 方法1 sql
      //  List<Brand>  brandList =  categoryBrandMapper.selectBrandListByCategory(id);
        // 方法2 java
        // 大体思路，根据 category_id 得到 list<categoryBrand>,然后得到 brand_id 集合，从而得到 list<brand>
       //  List<CategoryBrand> categoryBrandList = categoryBrandMapper.selectList(new LambdaQueryWrapper<CategoryBrand>().eq(CategoryBrand::getCategoryId, id));
         List<CategoryBrand> categoryBrandList = categoryBrandMapper.selectList(new LambdaQueryWrapper<CategoryBrand>().eq(CategoryBrand::getCategoryId, id));

        List<Brand> brandList1 = categoryBrandList.stream().map(brand -> brandMapper.selectOne(new LambdaQueryWrapper<Brand>().eq(Brand::getId, brand.getBrandId()))).toList();

        return brandList1;
    }



}
